package com.jzit168.library_retrofit

import com.jzit168.library_retrofit.interceptors.LoggingInterceptor
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 *@Desc: 网络请求工具
 *@Author: Android Developer
 *@Date: 2020/10/15
 *
 **/
object RetrofitFactory {

    fun <T> create(
        url: String,
        clazz: Class<T>,
        vararg interceptor: Interceptor
    ): T = init(url, *interceptor).create(clazz)

    private fun init(
        url: String,
        vararg interceptor: Interceptor
    ): Retrofit {
        return Retrofit.Builder()
            .baseUrl(url)
            .client(OkHttpClientFactory.init(*interceptor))
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }
}

object OkHttpClientFactory {

    fun init(vararg interceptors: Interceptor) = OkHttpClient.Builder().run {
        if (!interceptors.contains(LoggingInterceptor.show(true))) {
            addInterceptor(LoggingInterceptor.show(true))
        }
        interceptors.forEach {
            addInterceptor(it)
        }
        writeTimeout(8, TimeUnit.SECONDS)
        readTimeout(8, TimeUnit.SECONDS)
        callTimeout(8, TimeUnit.SECONDS)
        build()
    }
}